package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.util.RequiredPermission;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session中用户信息
        Employee emp = (Employee) request.getSession().getAttribute("EMP_IN_SESSION");
        //判断是否超管
        if(emp.isAdmin()){
            return true;
        }

        //handler是否是handlerMethod,代表被拦截的就是处理方法
        if(handler instanceof HandlerMethod){
            HandlerMethod method = (HandlerMethod) handler;
            //从方法上获取权限注解
            RequiredPermission annotation = method.getMethodAnnotation(RequiredPermission.class);
            //判断该方法上是否贴有权限注解
            if (annotation==null) {
                return true;
            }
            //获取当前用户拥有的权限
            List<String> expressions = (List<String>)request.getSession().getAttribute("EXPRESSION_IN_SESSION");
            //获取权限注解中的表达式
            String expression = annotation.expression();
            if(!expressions.contains(expression)){
                //跳转到nopermission页面(请求转发,不会经过视图解析器)
                //request.getRequestDispatcher("/WEB-INF/views/common/nopermission.ftl");
                response.sendRedirect("/nopermission");
                return false;
            }
        }
        //还有静态资源
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
